import axios from 'axios'
import store from '@/store'
import { Toast, Dialog } from 'vant'
// 根据环境不同引入不同api地址
import { baseApi, picApi } from '@/config'

axios.defaults.headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
const service = axios.create({
  // 不使用这里改请求
  // baseURL: baseApi, // url = base api url + request url
  // baseURL: '/api', // url = base api url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout  需改成60秒
})

// request拦截器 request interceptor
service.interceptors.request.use(
  config => {
    let prefix = config.urlType || 'api'
    switch (prefix) {
      case 'api':

        config.url = baseApi + config.url
        //    config.url = '/api' + config.url
        break
      case 'pic':
         config.url = picApi + config.url
        //   config.url = '/pic' + config.url
        break
    }

    // 不传递默认开启loading
    if (!config.hideloading) {
      // loading
      Toast.loading({
        forbidClick: true,
        duration: 60000
      })
    }
    if (store.getters.token) {
      config.headers['X-Token'] = ''
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// respone拦截器
service.interceptors.response.use(
  response => {
    Toast.clear()
    const res = response.data
    if (res.status && res.status !== 200) {
      // 登录超时,重新登录
      if (res.status === 401) {
        store.dispatch('FedLogOut').then(() => {
          location.reload()
        })
      }
      return Promise.reject(res || 'error')
    } else {
      if (res.code == '200') {
        return Promise.resolve(res)
      } else {
        Dialog.alert({
          title: '错误信息',
          message: res.msg
        })
        return Promise.reject(res)
      }
    }
  },
  error => {
    Toast.clear()
    Dialog.alert({
      title: '错误信息',
      message: '出现未知错误'
    })
    return Promise.reject({ code: 600, msg: error })
  }
)
export default service
